import 'package:flutter/material.dart';
import 'package:whale/helper/route/route_navigator.dart';

import '../../../../helper/utils/httputils/http_man.dart';
import '../../../../helper/utils/httputils/urlpath.dart';
import '../../../../helper/utils/util.dart';
import '../../../../helper/utils/validate.dart';
import 'index.dart';

class RegisterController extends GetxController {
  RegisterController();

  final state = RegisterState();

  void actionRegister() {
    if (state.account.isEmpty) {
      Hud.toast('请输入手机号');
      state.accountError = '请输入手机号';
      update();
      return;
    }
    if (state.smCode.isEmpty) {
      Hud.toast('请输入验证码');
      return;
    }

    if (state.smCode.length != 6) {
      Hud.toast('请输入正确的验证码');
      return;
    }

    if (state.pwdCtrl.text.isEmpty) {
      Hud.toast('请输入密码');
      state.pwdError = '请输入密码';
      update();
      return;
    }
    if (state.pwd2Ctrl.text.isEmpty) {
      Hud.toast('请输入确认密码');
      return;
    }
    if (state.pwdCtrl.text != state.pwd2Ctrl.text) {
      Hud.toast('两次密码不一致');
      return;
    }

    if (!Validate.matchPwd(input: state.pwdCtrl.text)) {
      Hud.toast('请输入至少8位密码，密码必须包含大小写');
      return;
    }

    register();
  }

  void register() async {
    var res = await Api.register(
      code: state.smCode,
      password: state.pwdCtrl.text,
      telephone: state.account,
    );
    if (res.isSuccess) {
      var data = res.data;
      if (data is Map<String, dynamic>) {
        var status = data['status'].toString();
        if (status == '0') {
          Hud.toast('注册成功');
          Get.backDelay();
        } else {
          Hud.toast(data['tips'] ?? '注册失败');
        }
      }
    } else {
      Hud.toast(res.msg);
    }
  }

  Future<bool> sendCode() async {
    if (state.account.isEmpty) {
      Hud.toast('请输入账号');
      state.accountError = '请输入账号';
      update();
      return false;
    }
    var res = await HttpMan.instance.post(UrlPath.sendCode, args: {
      "oneParam": state.account,
      "sendType": 1,
      "check": '0',
      'tenantId': '',
    });
    if (res.isSuccess) {
      return true;
    } else {
      Hud.toast(res.msg);
      return false;
    }
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.pwdCtrl = TextEditingController();
    state.pwd2Ctrl = TextEditingController();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
